<template>
	<view class="detail">
		<uni-nav-bar left-icon="left" @clickLeft="back" fixed statusBar="" title="明细" :border="false" backgroundColor="#ffcd54" color="#fff"></uni-nav-bar>
		<scroll-view
		scroll-y="true"
		style="height: 100vh;"
		@scrolltolower="scrolltolower"
		:refresher-enabled="true"
		@refresherrefresh="refresherrefresh"
		:refresher-triggered="refresherStatus"
		refresher-background="#fecd55"
		refresher-default-style="white"
		>
			<view class="detail_box">
				<view class="detail_bg"></view>
				<view class="detail_content p25">
					<view class="statistics" >
						<view class="statistics_time" @click="$refs.pickerViewRefs.open()">
							<text>{{ selectedValue }}</text>
							<view class="calender_pos">
								<view class="triangle triangle_color"></view>
							</view>
						</view>
						<view class="statistics_list">
							<view class="statistics_item">
								<view class="statistics_item_text">支出(元)</view>
								<view class="statistics_item_value" style="color: #3bb16e;">{{ totalExpend }}</view>
							</view>
							<view class="statistics_item">
								<view class="statistics_item_text">收入(元)</view>
								<view class="statistics_item_value" style="color: #f35d33;">{{ totalIncome }}</view>
							</view>
							<view class="statistics_item">
								<view class="statistics_item_text">结余(元)</view>
								<view class="statistics_item_value">{{ totalBalance }}</view>
							</view>
						</view>
					</view>
					<view class="" v-for="item in current" :key="item.tallyTime">
						<view class="dis_center_s mb20">
							<view class="">
								<text class="fs24 text-info mr15">{{ item.dayTitle }}</text>
								<text class="fs24 text-info">{{ item.week }}</text>
							</view>
							<view class="">
								<text class="fs24 text-info mr15">收{{ item.income }}</text>
								<text class="fs24 text-info">支{{ item.expend }}</text>
							</view>
						</view>
						<view class="dis_start" v-for="(tag, i) in item.children" :key="i">
							<view class="icon_box">
								<text :class="['iconfont', tag.icon]" style="font-size: 44rpx;color: #fe674a;"></text>
							</view>
							<view class="fl1 dis_center_s pt20 pl20 pb20 bb1">
								<view class="">
									<view class="fs30 fw700">{{ tag.text }}</view>
									<view>
										<text class="fs24 text-info mr10">{{ tag.meticulousTime }}</text>
										<text class="fs24 text-info">{{ tag.payText }}</text>
									</view>
								</view>
								<text class="fs30 fw700" :class="[tag.isType === '0' ? 'income_color' : 'expend_color']">{{ tag.isType === '0' ? `+${tag.spend}` : `-${tag.spend}` }}</text>
							</view>
						</view>
					</view>
					<uni-load-more :status="more"></uni-load-more>
				</view>
			</view>
		</scroll-view>
		<PickerView ref="pickerViewRefs" :options="[{ data: itemList }, { data: monthList }]" @confirm="confirmPicker" :pickerIndex="pickerIndex"/>
	</view>
</template>

<script>
	import PickerView from '@/components/uni-picker-view/index.vue'
	import store from '@/store/index.js'
	import moment from 'moment'
	import { icons } from '@/utils/dict-data.js'
	import { formatWeek, getYearTimes } from '@/utils/common.js'
	const uniAaccount = uniCloud.importObject('account')
	const uniTransaction = uniCloud.importObject('transaction')
	export default {
		components: {
			PickerView
		},
		data() {
			return {
				tableData: [],
				tableAll: [],
				current: [],
				accounts: [],
				page: 1,
				size: 10,
				totalExpend: 0,
				totalIncome: 0,
				totalBalance: 0,
				itemList: [],
				monthList: [],
				pickerIndex: [0, 0],
				loading: false,
				refresherStatus: false,
				more: 'more' // more loading noMore
			}
		},
		computed: {
			userInfo() {
				return store.state.user.userInfo
			},
			selectedValue() {
				if(this.itemList.length === 0 && this.monthList.length === 0) {
					const date = new Date()
					const year = date.getFullYear()
					const month = date.getMonth() + 1
					return `${year}-${this.zeroFill(month)}`
				} else {
					const [yearIndex, monthIndex] = this.pickerIndex
					return `${this.itemList[yearIndex].label}-${this.zeroFill(this.monthList[monthIndex].value)}`
				}
			}
		},
		onLoad() {
			this.initAccount()
			this.initPicker()
		},
		methods: {
			initPicker() {
				this.monthList = []
				this.itemList = getYearTimes()
				for (let i = 0; i < 11; i++) {
					this.monthList.push({ label: `${i + 1}月`, value: i + 1 })
				}
				this.pickerIndex = [0, new Date().getMonth()]
			},
			confirmPicker(event) {
				const value = event.detail.value || event.detail.__args__[0]
				this.pickerIndex = value
				this.page = 1
				this.size = 10
				setTimeout(() => {
					this.initExpenditure()
				}, 100)
			},
			initExpenditure() {
				uniTransaction.getPage({ userId: this.userInfo.uid, page: this.page, size: this.size, tallyTime: this.selectedValue }).then(res => {
					if(this.page === 1) {
						this.tableData = []
						this.current = []
					}
					if(res.data.length > 0) {
						this.tableData = [...this.tableData, ...res.data]
						const { totalExpend, totalIncome, list } = this.formatTransaction(this.tableData)
						 this.current = list
						 this.totalExpend = totalExpend.toFixed(2)
						 this.totalIncome = totalIncome.toFixed(2)
						 this.totalBalance = totalIncome - totalExpend < 0 ? 0 : (totalIncome - totalExpend).toFixed(2)
						this.page += 1
						this.more = 'more'
					} else {
						this.more = 'noMore'
					}
					this.loading = false
					this.refresherStatus = false
				}).catch(() => {
					this.more = 'more'
					this.loading = false
					this.refresherStatus = false
				})
			},
			getTransAll() {
				uniTransaction.get({ userId: this.userInfo.uid, tallyTime: this.selectedValue }).then(res => {
					this.tableAll = res.data
				})
			},
			initAccount() {
				uniAaccount.getAccout().then(res => {
					this.accounts = res.data.map(c => ({ text: c.accountName, value: c._id, balance: c.balance, accountType: c.accountType }))
					this.initExpenditure()
					this.getTransAll()
				})
			},
			formatTransaction(options) {
				return options.reduce((obj, row) => {
						const flag = ['1', '2'].includes(row.transactionType)
						const index = obj.list.findIndex(c => c.tallyTime === row.tallyTime)
						const find = icons.find(c => c.value === row.icon)
						const pay = this.accounts.find(c => c.value === row.accountId)
						const expend = flag ? Number(row.amount) : 0
						const income = !flag ? Number(row.amount) : 0
						obj.totalExpend += expend
						obj.totalIncome += income
						if(index === -1) {
							const [, num2, num3] = row.tallyTime.split('-')
							obj.list.push({
								dayTitle: `${this.zeroFill(num2)}-${this.zeroFill(num3)}`,
								week: formatWeek(moment(row.tallyTime).day()),
								income,
								expend,
								children: [
									{
										_id: row._id,
										text: find.text,
										icon: find.value,
										meticulousTime: row.meticulousTime,
										payText: pay.text,
										isType: row.transactionType,
										spend: row.amount
									}
								]
							})
						} else {
							const data = {
								_id: row._id,
								text: find.text,
								icon: find.value,
								meticulousTime: row.meticulousTime,
								isType: row.transactionType,
								payText: pay.text,
								spend: row.amount
							}
							obj.list[index].income += income;
							obj.list[index].expend += expend;
							obj.list[index].children.push(data)
						}
						return obj
					}, { totalExpend: 0, totalIncome: 0, list: [] })
			},
			zeroFill(num) {
				const count = Number(num)
				return count < 10 ? '0' + count : count
			},
			back() {
				uni.navigateBack()
			},
			// 上拉
			scrolltolower() {
				if(this.more === 'noMore') return
				this.more = 'loading'
				this.initExpenditure()
			},
			// 下拉
			refresherrefresh() {
				if(!this.loading) {
					this.loading = true
					this.refresherStatus = true
					this.page = 1
					this.size = 10
					this.pickerIndex = [0, new Date().getMonth()]
					this.initExpenditure()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.detail {
		.detail_box {
			position: relative;
			padding: 0 40rpx 50rpx;
			.detail_bg {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 300rpx;
				background-color: $uni-bg-color-common;
				z-index: -1;
			}
			.detail_content {
				background-color: #fff;
				border-radius: 12rpx;
				min-height: 84vh;
				box-shadow: 0 0 20rpx 5rpx #ccc;
			}
		}
	}
	.statistics {
		border-bottom: 1rpx solid #ddd;
		.statistics_time {
			position: relative;
			.calender_pos {
				position: absolute;
				top: 50%;
				left: 155rpx;
				transform: translateY(-50%);
				color: #fff;
			}
		}
		.statistics_list {
			display: flex;
			.statistics_item {
				flex: 1;
				padding: 25rpx 0;
				.statistics_item_text {
					font-size: 24rpx;
					color: #ccc;
					margin-bottom: 6rpx;
				}
				.statistics_item_value{
					font-size: 32rpx;
				}
			}
		}
	}
	.icon_box {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #ebebeb;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.expend_color {
		color:  #37af6b;
	}
	.income_color {
		color: #f57640;
	}
</style>